package com.lanou3g.ssoconsumer.interceptor;

import com.lanou3g.ssoconsumer.bean.UserInfo;
import com.lanou3g.ssoconsumer.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class OrderInterceptor implements HandlerInterceptor {


    @Value("${sso.login.url}")
    private String loginUrl;

    // http://localhost:8899/get_user_by_token/
    @Value("${sso.get_user_by_token.url}")
    private String getUserByTokenUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = response.getWriter();

        String uri = request.getRequestURL().toString();

        System.out.println(uri);

        String token = CookieUtils.getCookieValue(request, "USER-TT");
        if(token == null) {
            writer.println("<script>alert('会话超时，请重新登录！');location.href='"+loginUrl+"?redirectUrl="+uri+"';</script>");
            return false;
        }

        // 拿token，请求sso服务，换取真正的用户信息
        ResponseEntity<UserInfo> entity = restTemplate.getForEntity(getUserByTokenUrl + token, UserInfo.class);
        if(entity.getStatusCode().value() == 200) {
            UserInfo userInfo = entity.getBody();
            if(userInfo != null) {
                System.out.println("当前登录用户：" + userInfo.getNickName());
                return true;
            }
        }
        writer.println("<script>alert('无法获取登录信息，请重新登录！');location.href='"+loginUrl+"';</script>");
        return false;
    }
}
